using System;
using System.Collections.Generic;
using Magiq.Databases;
using Magiq.Delete;
using Magiq.Insert;
using Magiq.Query;
using Magiq.Providers.Sql.Support;
using Magiq.Update;

namespace Magiq.Providers.Sql
{
    public class MagiqToSql : MagiqToDatabases
    {
        private static LinqToSqlAdapter GetDatabaseAdapterFrom<T>(IEnumerable<T> source)
        {
            var dataContext = source.DataContext();
            return dataContext == null ? null : new LinqToSqlAdapter(dataContext);
        }

        protected override IOrmAdapter GetDatabaseAdapterFrom<T>(IUpdate<T> update)
        {
            return GetDatabaseAdapterFrom(update.Source);
        }

        protected override IOrmAdapter GetDatabaseAdapterFromDestination<TSource, TDestination, TNew>(
            IInsert<TSource, TDestination, TNew> insert)
        {
            if (insert.Destination.IsDataQuery())
                throw new InvalidOperationException("Items cannot be added to queries.");

            return GetDatabaseAdapterFrom(insert.Destination);
        }

        protected override IOrmAdapter GetDatabaseAdapterFrom<T>(IDelete<T> delete)
        {
            return GetDatabaseAdapterFrom(delete.Source);
        }

        protected override IOrmAdapter GetDatabaseAdapterFrom<T, TChild>(QueryInfo<T, TChild> queryInfo) 
        {
            if(queryInfo.IsEntitySet())
                return GetDatabaseAdapterFrom(queryInfo.ToEntitySet());
            return null;
        }

        protected override IOrmAdapter GetDatabaseAdapterFrom<TSource, TDestination, TNew>(
            IInsert<TSource, TDestination, TNew> insert)
        {
            return !insert.Source.IsLinqToSqlStuff() ? null : GetDatabaseAdapterFromDestination(insert);
        }
    }
}